if (Meteor.is_client) {
  
  var openWindow = function(){
    var specs = [
          "channelmode=no",
          "directories=no",
          "fullscreen=no",
          "height=700",
          "location=no",
          "menubar=no",
          "resizable=no",
          "scrollbars=no",
          "status=no",
          "titlebar=yes",
          "toolbar=no",
          "width=900"
        ],
        win = window.open('/preview/index.html?debug=true', 'preview', specs.join(','), false);
    
    win.focus();
    
    return win;
  };

  var CertmasterRouter = Backbone.Router.extend({
    
    routes: {
      "":                   "index",
      "certificates":       "certificates",
      "certificate/:id":    "certificate",
      "preview/:id":        "preview"
    },
    
    index: function(){
      $("#container").html(Meteor.ui.render(function(){
          return Template.Splash();
        })
      );
    },
    
    certificates: function(){
      var certs = Certificates.find({});
      
      Session.set("current_certificate", null);
      Session.set("cert_editor", null);
      Session.set("inst_editor", null);
      
      $("#navbar_container").html(Meteor.ui.render(function(){
        return Template.Navbar();
      }));
      
      $("#container").html(Meteor.ui.render(function(){
        certs.count();
        return Template.Certificates(certs);
      }.bind(this)));
      
      // Tablesorter stuff... Needs to have the rendered view available when instantiated
      // (thus, the setTimeout for now.)
      
      setTimeout(function(){
        $('#certificates-table').tablesorter({
          headers: {
            0: { sorter: 'true' },
            1: { sorter: 'true' },
            2: { sorter: false }
          }
        })
        .bind('sortEnd', function(){
          var self = $(this),
              header_row = self.find('th[class*=headerSort]'),
              header_direction = header_row.attr('class').split(' ')[1].replace('headerSort', '');
          
          self.find('th').children('i').attr('class', '');
          
          header_row.children('i').toggleClass('icon-arrow-' + header_direction.toLowerCase());
        });

      }, 1500);
       
    },
    
    certificate: function(id){
      var cert,
          blank_cert;
          
      switch(id){
      case 'new':
        blank_cert = new DefaultCertificate();
        id = Certificates.insert(blank_cert);
        break;
        
      default:
        
      }
      
      setTimeout(function(){
        cert = Certificates.find(id).fetch()[0];

        Session.set("current_certificate", cert);

        $("#container").html(Meteor.ui.render(function(){
          return Template.certificate_form_view(cert);
        }.bind(this)));

        head.ready('theme', function(){
          var cert_editor = ace.edit('certificate_markup'),
              inst_editor = ace.edit('instructions_markup'),
              HtmlMode = require("ace/mode/html").Mode;
              
          //editor.setTheme("ace/theme/solarized_dark");
          cert_editor.getSession().setMode(new HtmlMode());
          inst_editor.getSession().setMode(new HtmlMode());
          
          Session.set('cert_editor', cert_editor);
          Session.set('inst_editor', inst_editor);
        });

        head.js(
          {ace: '/ace/build/src/ace.js'},
          {mode: '/ace/build/src/mode-html.js'},
          {theme: '/ace/build/src/theme-solarized_dark.js'}
        );
      }, 500);
      
    },
    
    preview: function(id){
      
      var win = openWindow();
          
      Session.set('current_certificate', id);
                          
      setTimeout(function(){
        
        win.$('body').html(Meteor.ui.render(function(){
          var cert = Certificates.findOne(Session.get('current_certificate')),
              certificate_template = window.Handlebars.evaluate(cert.certificate_markup, cert),
              instructions_template = window.Handlebars.evaluate(cert.instructions_markup, cert);
          
          console.log(certificate_template(cert));
          // cert.instructions_rendered = Template.PreviewInstructions(cert);
          // return Template.PreviewBody(cert);
        }));
        
        router.navigate('/certificates', {trigger: true});
        
      }, 500);
    }
    
  });
  
  Meteor.startup(function () {
    $(function(){
      window.router = new CertmasterRouter();
      Backbone.history.start({
        pushState: true,
        silent: false
      });
    });
  });
  
}

if (Meteor.is_server) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}